from gameServer import gameServer
from rCube import RCube
from random import Random
from soundServer import sound

class ItemFactory(RCube):
    spawnList = []
    spawnListDirty = True
    
    def __init__(self):
        RCube.__init__(self)
        
        if(ItemFactory.spawnListDirty):
            self.spawnListReset()
        self.rand = Random()
    
    def spawnListReset(self):
        ItemFactory.spawnListDirty = False
        ItemFactory.spawnList = []
        ItemFactory.spawnList.append(["items.spikeHat"   , "SpikeHat"   , -1, 0, 0, 0])
        ItemFactory.spawnList.append(["items.extraFast"  , "ExtraFast"  , -1, 0, 0, 0])
        ItemFactory.spawnList.append(["items.gun"        , "Gun"        , -1, 0, 0, 0])
        ItemFactory.spawnList.append(["items.deathMace"  , "DeathMace"  ,  2, 0, 0, 0])
        ItemFactory.spawnList.append(["items.invincible" , "Invincible" ,  1, 0, 0, 0])
        ItemFactory.spawnList.append(["items.windmill"   , "Windmill"   , -1, 0, 0, 0])
        ItemFactory.spawnList.append(["items.clusterBomb", "ClusterBomb",  3, 0, 0, 0])
    
    def spawnListCalcPercentage(self):
        ItemFactory.spawnListDirty = True
                
        sum = 0
        for i in ItemFactory.spawnList:
            if(i[2] <= -1 or i[2] > i[3]):
                sum += (1 + i[3])
        for i in ItemFactory.spawnList:
            if(i[2] <= -1 or i[2] > i[3]):
                i[4] = sum - i[3]
            else:
                i[4] = 0
        sum = 0
        for i in ItemFactory.spawnList:
            sum += i[4]
        for i in ItemFactory.spawnList:
            i[5] = i[4]/float(sum)
        #self.printSpawnList()
                    
    def printSpawnList(self):
        for i in ItemFactory.spawnList:
            print i[1].ljust(10), str(i[2]).rjust(3), str(i[3]).rjust(3), str(i[4]).rjust(3), str(round(i[5],3)).rjust(5)
        print ""
    
    def spawnItem(self):
        self.spawnListCalcPercentage()
        
        v = self.rand.random()
        index = -1
        while v > 0 and index < len(ItemFactory.spawnList)-1:
            index += 1
            v -= ItemFactory.spawnList[index][5]
        ItemFactory.spawnList[index][3] += 1
        execstr = 'from %s import %s as item' % (ItemFactory.spawnList[index][0], ItemFactory.spawnList[index][1])
        exec(execstr)
        i = gameServer.addObject(gameServer.makeObjectName(self.spawnList[index][1] + "_"), item())
        sound.play("item_spawn")
        return i